<template>
    <div id="devicePosition">
      <el-container v-loading="loading"  element-loading-text="拼命加载中">
        <el-aside width="280px"   style="background-color: #ffffff;border: 1px solid #e5e5e5;">
          <DeviceTree :clickEvent="clickEvent" :getParams="getParams"  :contextMenuEvent="contextMenuEvent"></DeviceTree>
        </el-aside>
        <el-container>
          <el-header>
            <div style="display:flex;align-items: center;">
              分屏:
              <svg class="iconfontSvg"     aria-hidden="true" :class="{active:spiltIndex === 0}" @click="spiltIndex=0">
                <use xlink:href="#icon-a-mti-1fenpingshi" color="red"></use>
              </svg>
              <svg class="iconfontSvg"     aria-hidden="true" :class="{active: spiltIndex === 1}" @click="spiltIndex=1">
                <use xlink:href="#icon-a-mti-4fenpingshi" color="red"></use>
              </svg>
              <svg class="iconfontSvg"     aria-hidden="true" :class="{active: spiltIndex === 2}" @click="spiltIndex=2">
                <use xlink:href="#icon-a-mti-6fenpingshi" color="red"></use>
              </svg>
              <svg class="iconfontSvg"     aria-hidden="true" :class="{active: spiltIndex === 3}" @click="spiltIndex=3">
                <use xlink:href="#icon-a-mti-9fenpingshi" color="red"></use>
              </svg>
              <i class="el-icon-full-screen btn" @click="fullScreen()"/>
              <div>
            </div>
            </div>
            <div style="display:flex;align-items: center;margin-left: auto;">
                    <el-button size="mini" v-if="$route.query.type === 'KB'"  @click="chooseButton(1)">返回</el-button>
                    <el-button size="mini" v-if="$route.query.type === 'PB'"  @click="chooseButton(2)">返回</el-button>
                    <!-- <el-button size="mini" v-if="$route.query.type === 'PB'" @click="chooseButton(4)">行为轨迹</el-button> -->
            </div>
          </el-header>
          <el-main style="padding: 0; margin: 0 auto; background-color: #a9a8a8" >
            <div 
            class="playBox"
            ref="playBox"
            :style="{
              gridTemplateColumns: layout[spiltIndex].columns,
              gridTemplateRows: layout[spiltIndex].rows,
              gap: '4px',
              backgroundColor: '#a9a8a8'
            }">
              <div v-for="i in layout[spiltIndex].spilt" :key="i" class="play-box" :class="getPlayerClass(spiltIndex, i)"
                   @click="playerIdx = (i-1)">
                <player :loop="false" :url="videoUrl[i - 1]"></player>
              </div>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </template>
  <script>
  import player from './common/easyPlayer.vue'
  import DeviceTree from './common/elTree.vue'
  import screenfull from "screenfull";
  import { deviceGetPlayUrl } from "@/api/pageVideoWitness"
  import { witnessDeviceStopPlay} from "@/api/pageVideoWitness"
  export default {
    name: "live",
    props:[],
    components: {
       player, 
       DeviceTree
    },
  
    data() {
      return {
        videoUrl: [''],
        spiltIndex: 1,//分屏
        playerIdx: 0,//激活播放器
        updateLooper: 0, //数据刷新轮训标志
        count: 15,
        total: 0,
        //channel
        loading: false,
        layout: [
          {
            spilt: 1,
            columns: "1fr",
            rows: "1fr",
            style: function (){}
          },
          {
            spilt: 4,
            columns: "1fr 1fr",
            rows: "1fr 1fr",
            style: function (){}
          },
          {
            spilt: 6,
            columns: "1fr 1fr 1fr",
            rows: "1fr 1fr 1fr",
            style: function (index){
              console.log(index)
              if (index === 0) {
                return {
                  gridColumn: ' 1 / span 2',
                  gridRow: ' 1 / span 2',
                }
              }
            }
  
          },
          {
            spilt: 9,
            columns: "1fr 1fr 1fr",
            rows: "1fr 1fr 1fr",
            style: function (){}
          },
        ],
        getParams:{
          taskType:'PB',
          status:'JZZ', // JZZ见证中、YWC已完成
          deviceType:'CAMERA'
        },
        deviceType:'',
      };
    },
    mounted() {
  
    },
    created() {
   
     
    },
  
    computed: {
      liveStyle() {
        let style = {width: '100%', height: '100%'}
        switch (this.spilt) {
          case 4:
            style = {width: '49%', height: '49%'}
            break
          case 9:
            style = {width: '32%', height: '32%'}
            break
        }
        this.$nextTick(() => {
          for (let i = 0; i < this.spilt; i++) {
            const player = this.$refs.player
            player && player[i] && player[i].updatePlayerDomSize()
          }
        })
        return style
      }
    },
    watch: {
      spilt(newValue) {
        console.log("切换画幅;" + newValue)
        let that = this
        for (let i = 1; i <= newValue; i++) {
          if (!that.$refs['player' + i]) {
            continue
          }
          this.$nextTick(() => {
            if (that.$refs['player' + i] instanceof Array) {
              that.$refs['player' + i][0].resize()
            } else {
              that.$refs['player' + i].resize()
            }
          })
  
        }
        window.localStorage.setItem('split', newValue)
      },
      '$route.fullPath': 'checkPlayByParam'
    },
    destroyed() {
      clearTimeout(this.updateLooper);
      this.handleStopPlay()

    },
    methods: {

      // 关闭视频播放按钮
      handleStopPlay(){
        const extractString =(str, start, end)=> {
        let startIndex = str.indexOf(start);
        let endIndex = str.indexOf(end, startIndex + start.length);
        return str.substring(startIndex !== -1 && endIndex !== -1 ? startIndex + start.length : 0, endIndex);
      }
      let newURLs = new Set([])
        this.videoUrl.forEach(x=>{
          newURLs.add(extractString(x,'live/','.live'))  
        })  
        witnessDeviceStopPlay([...newURLs]).then(res=>{
          console.log(res);
        })
      },
      


      chooseButton(num) {
        const { bdid,taskid} = this.$route.query
          if(num == 1){
            // 跳转到开标阶段
            this.$router.push({ path: '/witnessStage/kbStage',query:{bdid,taskid} });
          }
          if(num == 2){
            // 跳转到评标阶段
            this.$router.push({ path: '/witnessStage/pbStage',query:{bdid,taskid} });
          }
          if (num == 4) {
              this.$router.push({ path: '/witness/pageBehaviorTrace',query:{bdid,taskid}});
          }
       },
      destroy(idx) {
        console.log(idx);
        this.clear(idx.substring(idx.length - 1))
      },
      clickEvent (data,deviceType) {
        this.deviceType = deviceType
        if(data.level > 1){
          this.sendDevicePush(data.deviceId)
         
        }else{
          const arr = data.deviceList.map(x=>x.deviceId)
          this.sendDevicePushAll(arr)
        }
       
      },
      getPlayerClass: function (splitIndex, i) {
        // console.log();
        // console.log(this.videoUrl);
        let classStr = "play-box-" + splitIndex + "-" +i
        if (this.playerIdx === (i-1)) {
          classStr += " redborder"
        }
        return classStr
      },
      contextMenuEvent: function (device, event, data, isCatalog) {

      },
      sendDevicePushAll(channelIds) {
      let num = 0
      const lenght =  channelIds.length
      if (lenght > 12){
        num = 4
      }
      if(9 < lenght <= 12){
        num = 4
      }
      if(6 < lenght <= 9 ){
        num = 3
      }
      if(4<lenght<=6){
        num = 2
      }
      if(lenght<=4){
        num = 1
      }
      // this.$emit('update:spiltIndex',num)
      this.spiltIndex = num
      channelIds.forEach((x,index) => {
        this.sendDevicePush(x,index);
      });
      },
    //通知设备上传媒体流
    sendDevicePush(channelId,idx) {
      
      this.save(channelId);
      let idxTmp = idx || this.playerIdx;
      deviceGetPlayUrl({deviceId:channelId,deviceType:this.deviceType})
        .then((res) => {
          if (res.code === 0 && res.data) {
            let videoUrl;
            if (location.protocol === "http:") {
              videoUrl = res.data.url;
            } else {
              videoUrl = res.data.url;
            }
            this.setPlayUrl(videoUrl, idxTmp);
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(function (e) {})
        .finally(() => {
          this.loading = false;
        });
    },
      //通知设备上传媒体流
      // sendDevicePush: function (channelId) {
      //   this.save(channelId)
      //   let idxTmp = this.playerIdx

      //   deviceGetPlayUrl(channelId).then((res)=> {
      //     console.log('res',res);
          
      //     if (res.code === 0 && res.data) {
      //       let videoUrl;
      //       if (location.protocol === "http:") {
      //         videoUrl = res.data.url;
      //       } else {
      //         videoUrl = res.data.url;
      //       }
      //       this.setPlayUrl(videoUrl, idxTmp);
      //     } else {
      //       this.$message.error(res.data.msg);
      //     }
      //   }).catch(function (e) {
      //   }).finally(() => {
      //     this.loading = false
      //   });
      // },
      setPlayUrl(url, idx) {
        this.$set(this.videoUrl, idx, url)
        let _this = this
        setTimeout(() => {
          window.localStorage.setItem('videoUrl', JSON.stringify(_this.videoUrl))
        }, 100)
  
      },
      checkPlayByParam() {
        let channelId = this.$route.query
        if (channelId) {
          this.sendDevicePush(channelId)
        }
      },
      shot(e) {
        // console.log(e)
        // send({code:'image',data:e})
        var base64ToBlob = function (code) {
          let parts = code.split(';base64,');
          let contentType = parts[0].split(':')[1];
          let raw = window.atob(parts[1]);
          let rawLength = raw.length;
          let uInt8Array = new Uint8Array(rawLength);
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
          }
          return new Blob([uInt8Array], {
            type: contentType
          });
        };
        let aLink = document.createElement('a');
        let blob = base64ToBlob(e); //new Blob([content]);
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = '截图';
        aLink.href = URL.createObjectURL(blob);
        aLink.click();
      },
      save(item) {
        let dataStr = window.localStorage.getItem('playData') || '[]'
        let data = JSON.parse(dataStr);
        data[this.playerIdx] = item
        window.localStorage.setItem('playData', JSON.stringify(data))
      },
      clear(idx) {
        let dataStr = window.localStorage.getItem('playData') || '[]'
        let data = JSON.parse(dataStr);
        data[idx - 1] = null;
        console.log(data);
        window.localStorage.setItem('playData', JSON.stringify(data))
      },
      fullScreen: function (){
        if (screenfull.isEnabled) {
          screenfull.toggle(this.$refs.playBox);
        }
      }
    }
  };
  </script>
  <style scoped lang="scss">
  #devicePosition{
    height: calc(100vh - 150px);
    // border: 1px solid red;
  }
  .el-aside{
    // border: 1px solid red;
    // box-sizing: border-box;
  }
  .el-header{
    display: flex;
  }
  .el-main{
    // border: 1px solid green;
  }
  //  图标样式
  .iconfontSvg{
    width: 28px;
    height:28px;
    fill:#303030;
    margin-left: 10px;
    
  }
  .iconfontSvg.active{
    fill:#0984ff !important;
  
  }
  .el-icon-full-screen{
    font-size: 28px;
    margin-left: 10px;
  }
  .el-main{
    width: 100%;
  }
  .playBox{
    width: 100%;
    height: 100%;

    display: grid;
    justify-self: center;
}
.redborder {
  border: 4px solid rgb(0, 198, 255) !important;
  
}
.play-box {
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;

}
.play-box-2-1 {
  grid-column: 1 / span 2;
  grid-row: 1 / span 2;
}
 
  </style>
  